package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/3/29
 * 该案例演示了以批的形式对有界流数据进行处理
 */
public class Flink01_WC_Batch_Bound {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定批处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //TODO 2.从指定的文件中读取数据
        DataSource<String> dataSource = env.readTextFile("D:\\dev\\workspace\\bigdata-1030\\input\\word.txt");
        //TODO 3.对当前行数据进行扁平化处理  并转换类型   String->tuple2<String,Long>
        FlatMapOperator<String, Tuple2<String, Long>> flatMapDS = dataSource.flatMap(
                new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String lineStr, Collector<Tuple2<String, Long>> out) throws Exception {
                        //使用空格分隔当前行数据
                        String[] words = lineStr.split(" ");
                        for (String word : words) {
                            //向下游传递数据
                            out.collect(Tuple2.of(word, 1L));
                        }
                    }
                }
        );
        //TODO 4.按照单词进行分组
        UnsortedGrouping<Tuple2<String, Long>> groupDS = flatMapDS.groupBy(0);
        //TODO 5.对单词次数进行求和
        AggregateOperator<Tuple2<String, Long>> sumDS = groupDS.sum(1);
        //TODO 6.打印输出结果
        sumDS.print();
    }
}